import React from 'react';
import eventBus from '@/utils/eventBus';

const loadingQueue = [];
const formatKey = (obj = {}) => JSON.stringify(obj);

// 通过订阅request获得全局的接口请求loading状态，但是太hack了...
const useGlobalLoading = () => {
    const [, setChange] = React.useState(0);

    const addCallback = React.useCallback(
        obj => {
            loadingQueue.push(formatKey(obj)); // 即使是相同的key也需要推入
            setChange(Math.random());
        },
        [setChange]
    );

    const removeCallback = React.useCallback(
        obj => {
            const existIndex = loadingQueue.findIndex(item => item === formatKey(obj));
            loadingQueue.splice(existIndex, 1);
            setChange(Math.random());
        },
        [setChange]
    );

    return {
        addCallback,
        removeCallback,
        loading: loadingQueue.length > 0
    };
};

export const ADD_GLOBAL_LOADING = '__addGlobalLoading';
export const REMOVE_GLOBAL_LOADING = '__removeGlobalLoading';

export const loadingPub = (event, value) => {
    eventBus.emit(event, value);
};

const loadingSub = (event, callback) => {
    eventBus.addListener(event, value => {
        callback(value);
    });
};

const loadingUnSub = (event, callback) => {
    eventBus.removeListener(event, value => {
        callback(value);
    });
};

export const withGlobalLoadingHook = React.memo(Component => props => {
    const { addCallback, removeCallback } = useGlobalLoading();
    React.useEffect(() => {
        loadingSub(ADD_GLOBAL_LOADING, addCallback);
        loadingSub(REMOVE_GLOBAL_LOADING, removeCallback);
        return () => {
            loadingUnSub(ADD_GLOBAL_LOADING, addCallback);
            loadingUnSub(REMOVE_GLOBAL_LOADING, removeCallback);
        };
    }, []);
    return <Component {...props} />;
});

export default useGlobalLoading;
